import { Component, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { STComponent, STColumn, STChange, STRequestOptions, STData } from '@delon/abc/st';
import { SFSchema, SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { delay } from 'rxjs/operators';
import { BasicTableComponent } from 'src/app/routes/commom';

import { TicketService } from '../../services/ticket.service';
import { TicketManagementApplyRecordListTicketComponent } from './apply-record-list-ticket/apply-record-list-ticket.component';
import { PrintOrderModalComponent } from './print-order-modal/print-order-modal.component';
import { RequestedInvoiceModalComponent } from './requested-invoice-modal/requested-invoice-modal.component';
import { UpdateAddressModalComponent } from './update-address-modal/update-address-modal.component';

@Component({
  selector: 'app-invoice-requested',
  templateUrl: './invoice-requested.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class InvoiceRequestedComponent extends BasicTableComponent {
  @ViewChild('rejectModal', { static: false })
  rejectModal!: any;
  resourceStatus: any = '1';
  columns: STColumn[] = this.initST();
  schema: SFSchema = this.initSF();

  totalCallNo = 0;
  selectedRows: any[] = [];

  rejectReason = '';
  constructor(
    public service: TicketService,
    private nzModalService: NzModalService,
    private router: Router,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  search() {
    this.st?.load(1);
  }

  beforeReq = (requestOptions: STRequestOptions) => {
    if (this.resourceStatus) {
      Object.assign(requestOptions.body, { sts: this.resourceStatus });
    }
    if (this.sf) {
      Object.assign(requestOptions.body, {
        ...this.sf?.value,
        createTime: {
          start: this.sf?.value?.createTime?.[0] || '',
          end: this.sf?.value?.createTime?.[1] || ''
        }
      });
    }
    return requestOptions;
  };

  afterRes = (data: any[], rawData?: any) => {
    this.totalCallNo = 0;
    this.selectedRows = [];
    return data.map(item => ({
      ...item,
      disabled: item.expressHSts
    }));
  };

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox!;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.applyAmount, 0).toFixed(2);
        break;
    }
  }

  rejectAction(item: any[]) {
    this.rejectReason = '';
    if (item.length <= 0) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    if (item.find(item => item.sts !== '1')) {
      this.service.msgSrv.warning('请勿选择非待处理订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '驳回',
      nzContent: this.rejectModal,
      nzOkLoading: this.service.http.loading,
      nzOnOk: () => {
        if (!this.rejectReason) {
          this.service.msgSrv.warning('请填写驳回原因');
          return false;
        }
        let ids = item.map(row => row.id);
        this.service.request(this.service.$api_reject_invoice, { id: ids, rejectContent: this.rejectReason }).subscribe(res => {
          if (res) {
            this.service.msgSrv.success('驳回成功');
            modal.destroy(true);
          }
        });

        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  /**
   * 修改地址
   * @param item
   */
  changeAddress(item: any[]) {
    this.rejectReason = '';
    if (item.length <= 0) {
      this.service.msgSrv.warning('请选择开票申请');
      return;
    }
    // if (item.find(item => item.sts !== '1')) {
    //   this.service.msgSrv.warning('请勿选择非待处理订单');
    //   return;
    // }
    const modal = this.nzModalService.create({
      nzTitle: '修改地址',
      nzContent: UpdateAddressModalComponent,
      nzOkLoading: this.service.http.loading,
      nzOnOk: component => {
        if (!component.sf.valid) {
          component.sf.validator({ emitError: true });
          // this.service.msgSrv.warning('表单校验错误');
          return false;
        }
        this.service
          .request(this.service.$api_update_invoice_address, {
            ...component.sf.value,
            ids: item.map(i => i.id)
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('修改成功');
              modal.destroy(true);
            }
          });

        return false;
      }
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  printOrder(item: any[]) {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    if (this.selectedRows.find(item => item.sts !== '3')) {
      this.service.msgSrv.warning('请勿选择非已完成订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '快递下单',
      nzContent: PrintOrderModalComponent,
      nzWidth: 650,
      nzComponentParams: { vatappcodes: this.selectedRows.map(item => item.vatappcode) },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }

  showReason(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看原因',
      nzContent: '运单数据异常，暂时无法开票，请联系客服400-xxxx-xxxx',
      nzFooter: [
        {
          label: '关闭',
          type: 'primary',
          onClick: () => {
            modal.destroy();
          }
        }
      ]
    });
  }

  batchRequested() {
    if (this.selectedRows?.length <= 0) {
      this.service.msgSrv.warning('请选择订单');
      return;
    }
    if (this.selectedRows.find(item => item.sts !== '1')) {
      this.service.msgSrv.warning('请勿选择非待处理订单');
      return;
    }
    const modal = this.nzModalService.create({
      nzTitle: '开票',
      nzContent: '确认对所有申请单进行批量开票？',
      nzFooter: [
        {
          type: 'default',
          label: '手工处理',
          onClick: () => {
            const params = {
              ficoVatappHVOList: this.selectedRows.map(item => {
                const i = Object.assign({}, { ...item });
                delete i._values;
                delete i._rowClassName;
                delete i.checked;
                delete i.disabled;
                return i;
              })
              // id: this.id
            };
            this.service.request(this.service.$api_get_applyBatchFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.service.msgSrv.success('提交成功！');
                modal.destroy();
                this.st.load(1);
              }
            });
          }
        },
        {
          type: 'primary',
          label: '自动开票',
          onClick: () => {
            const params = {
              ficoVatappHVOList: this.selectedRows.map(item => {
                const i = Object.assign({}, { ...item });
                delete i._values;
                delete i._rowClassName;
                delete i.checked;
                delete i.disabled;
                return i;
              })
              // id: this.id
            };
            this.service.request(this.service.$api_get_applyBatchFicoVatinv, params).subscribe((res: any) => {
              if (res) {
                this.service.msgSrv.success('提交成功！');
                modal.destroy();
                this.st.load(1);
              }
            });
          }
        }
      ]
    });
  }

  requestedInvoiceAction(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '开票受理',
      nzContent: RequestedInvoiceModalComponent,
      nzNoAnimation: true,
      nzWidth: 1200,
      nzComponentParams: {
        id: item.id
      },
      nzFooter: null
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load(1);
      }
    });
  }

  downloadPdf(item: any) {
    if (item?.reconciliationUrl) {
      this.service.reviewPDF(item.reconciliationUrl);
    } else {
      this.service
        .request(this.service.$api_downloadPdf, { vatappHId: item.id })
        .pipe(delay(3000))
        .subscribe(res => {
          if (res?.esignFlowId) {
            this.service
              .request(this.service.$api_download_Reconciliatio_pdf, { vatappHId: item.id, esignFlowId: res.esignFlowId })
              .subscribe(rs => {
                if (rs?.reconciliationUrl) {
                  this.service.reviewPDF(rs.reconciliationUrl);
                } else {
                  // this.service.msgSrv.warning('获取对账单失败');
                }
                this.st.load(1);
              });
          }
          // this.service.msgSrv.warning('获取对账单失败');
        });
    }
  }

  // 导出
  exprot() {
    this.service.exportStart({ ...this.sf?.value, pageSize: -1 }, this.service.$api_export_invoice_requested_page);
  }

  private initSF(): SFSchema {
    return {
      properties: {
        expand: {
          type: 'boolean',
          ui: {
            hidden: true
          }
        },
        vatappcode: {
          type: 'string',
          title: '申请编号',
          ui: {
            placeholder: '请输入'
          }
        },
        billHCode: {
          type: 'string',
          title: '订单号',
          ui: {
            placeholder: '请输入'
          }
        },
        feeHCode: {
          type: 'string',
          title: '费用号',
          ui: {
            placeholder: '请输入'
          }
        },
        projectId: {
          title: '项目',
          type: 'string',
          default: '',
          ui: {
            widget: 'select',
            asyncData: () => this.service.getEnterpriseProject()
          }
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          },
          default: ''
        },
        otherremarks: {
          type: 'string',
          title: '其他需求'
        },
        createTime: {
          title: '申请时间',
          type: 'string',
          ui: {
            widget: 'sl-from-to-search',
            format: 'yyyy-MM-dd',
            placeholder: '请选择',
            nzShowTime: true
          } as SFDateWidgetSchema
        },
        isdetail: {
          type: 'string',
          title: '销货清单',
          enum: [
            { label: '全部', value: '' },
            { label: '需要', value: 1 },
            { label: '不需要', value: 0 }
          ],
          ui: {
            widget: 'select',
            placeholder: '请选择'
          },
          default: ''
        },
        arto: {
          type: 'string',
          title: '货主名称',
          ui: {
            widget: 'select',
            serverSearch: true,
            searchDebounceTime: 300,
            searchLoadingText: '搜索中...',
            allowClear: true,
            onSearch: (q: any) => this.service.getEnterpriceList({ enterpriseName: q })
          }
        }
      }
    };
  }

  private initST(): STColumn[] {
    return [
      { title: '', index: 'key', type: 'checkbox' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return ((this.st.pi -1) * this.st.ps) + idx + 1 + ''
        } 
      },
      { title: '申请编号', render: 'vatappcode', width: 190 },
      { title: '发票类型', index: 'vatapptypeLabel', width: 140 },
      { title: '网络货运人', index: 'ltdName', width: 170 },
      { title: '货主名称', index: 'artoName', width: 170 },
      { title: '订单数', index: 'ordlines', width: 90 },
      {
        title: '申请金额',
        index: 'applyAmount',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.applyAmount }) }
      },
      {
        title: '运输费',
        index: 'fjfmoney2',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney2 }) }
      },
      {
        title: '附加费',
        index: 'fjfmoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.fjfmoney }) }
      },
      {
        title: '已开票金额',
        index: 'invoicedMoney',
        width: 150,
        type: 'widget',
        className: 'text-right',
        widget: {
          type: 'currency-chy',
          params: ({ record }) => ({ value: record.invoicedMoney })
        }
      },
      { title: '已开票张数', className: 'text-right', index: 'invoicedNum', width: 160 },
      { title: '开户行', index: 'bankName', width: 160 },
      { title: '银行账户', index: 'bankAccount', width: 140 },
      { title: '注册地址', index: 'registerAddr', width: 140 },
      { title: '注册电话', index: 'registerPhone', width: 130 },
      { title: '服务名称', index: 'vatnameLabel', width: 150 },
      {
        title: '销货清单',
        index: 'isdetail',
        width: 100,
        format: item => {
          return item.isdetail === 0 ? '不需要' : '需要';
        }
      },
      { title: '其他要求', index: 'otherremarks', width: 100 },
      { title: '申请人', index: 'applyName', width: 90 },
      { title: '申请时间', index: 'applyTime', type: 'date', width: 150 },
      {
        title: '快递是否下单成功',
        index: 'expressHSts',
        width: 170,
        className: 'text-center',
        type: 'enum',
        enum: { true: '是', false: '否' }
      },
      {
        title: '操作',
        width: 125,
        fixed: 'right',
        className: 'text-center',
        buttons: [
          { type: 'divider' },
          {
            text: '开票受理<br/>',
            click: item => this.requestedInvoiceAction(item),
            acl: { ability: ['TICKET-INVOICE-REQUESTED-requestedInvoiceAction'] },
            iif: item => item.sts === '1'
          },
          {
            text: '驳回申请<br/>',
            click: item => this.rejectAction([item]),
            acl: { ability: ['TICKET-INVOICE-REQUESTED-rejectAction'] },
            iif: item => item.sts === '1'
          },
          {
            text: '查看分票<br/>',
            click: _record => this.viewTicket(_record),
            acl: { ability: ['TICKET-INVOICE-REQUESTED-viewTicket'] },
            iif: item => item.sts == '3'
          },
          {
            text: '订单明细<br/>',
            acl: { ability: ['TICKET-INVOICE-REQUESTED-detail'] },
            click: item => this.router.navigate([`/ticket/invoice-requested/detail/${item?.id}`], { queryParams: { sts: item.sts } })
          },
          {
            text: '查看原因<br/>',
            click: item => this.showReason(item),
            acl: { ability: ['TICKET-INVOICE-REQUESTED-viewResult'] },
            iif: item => item.sts === '4'
          },
          {
            text: '下载对账单',
            iif: item => item.sts === '3',
            acl: { ability: ['TICKET-INVOICE-REQUESTED-downloadPDF'] },
            click: item => this.downloadPdf(item)
          }
        ]
      }
    ];
  }
  selectChange(e: any) {
    this.resourceStatus = e;
    this.initST();
    setTimeout(() => {
      this.st.load();
    }, 500);
  }
  viewTicket(item: any) {
    const modal = this.nzModalService.create({
      nzTitle: '查看分票',
      nzContent: TicketManagementApplyRecordListTicketComponent,
      nzNoAnimation: true,
      nzWidth: 900,
      nzComponentParams: { data: item },
      nzOnOk: com => {
        this.st?.load(1);
      },
    });
    modal.afterClose.subscribe(res => {
      if (res) {
        this.st.load();
      }
    });
  }
}
